package com.server.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.server.common.base.PathManager;
import com.server.common.base.ProjectInfor;
import com.server.common.base.SessionData;
import com.server.common.util.PPT_2_PDF_Util;
import com.server.common.util.PDF_2_Image_Util;
import com.server.common.util.PPT_2_JPG_2_PDF_Util;
import com.server.common.util.OfficeConverterUtil;
import com.server.service.IAttachmentService;
import com.server.web.JSONSerielizer;
import com.server.web.OutputUtil;
import com.server.web.SessionUtil;

@Controller
@RequestMapping("attach")
public class AttachmentController {

	@Autowired
	private IAttachmentService attachmentService;

	@RequestMapping("")
	public ModelAndView uploadPage() {
		File inputFile = new File("D:/PPT_test/pptfans_db0d9de941127e43b409.pptx");
		File outputFile = new File("D:/PPT_test/pptfans_db0d9de941127e43b409.pptx.pdf");
		PPT_2_PDF_Util.ppt2PDF(inputFile, outputFile);
		// pptConverter.ppt2PDF(inputFile,outputFile);
		ModelAndView mv = new ModelAndView("common/fileupload");
		mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
		return mv;
	}
	@RequestMapping("test")
	public ModelAndView test() {
		ModelAndView mv = new ModelAndView("common/knowledge_info_preview");
		mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
		return mv;
	}
	@RequestMapping("{actionType}/{actionId}")
	public ModelAndView attachPage(HttpServletRequest request,
			@PathVariable String actionType, @PathVariable Integer actionId) {
		ModelAndView mv = new ModelAndView("common/fileupload");
		mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
		mv.addObject("actionType",actionType);
		mv.addObject("actionId",actionId);
		return mv;
	}
	@RequestMapping("list/{actionType}/{actionId}")
	public void list(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String actionType, 
			@PathVariable Integer actionId){
		List<Map<String, Object>> list = attachmentService.getList(actionType, actionId.toString());
		OutputUtil.returnGridData(response, list.size(), JSONSerielizer.toJson(list, null, null));
	}

	@RequestMapping("upload/{inputName}/{fileTitle}/{actionType}/{actionId}")
	public void upload(HttpServletRequest request,
			HttpServletResponse response, @PathVariable String inputName,
			@PathVariable String fileTitle, @PathVariable String actionType,
			@PathVariable Integer actionId) {
		Boolean isSuccess = true;
		String errorInfo = "数据保存出错！";

		String userName = null;
		if (actionType.equals("avatar")) {
			userName = SessionUtil.getStringAttri(request, SessionData.nameKey);
		}else {
			userName = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		}
		
		if (StringUtils.isEmpty(userName)) {
			errorInfo = "未登录！";
			OutputUtil.returnSuccess(response, false, errorInfo);
			return;
		}

		// TODO 权限控制

		MultipartResolver resolver = new CommonsMultipartResolver(request
				.getSession().getServletContext());
		MultipartHttpServletRequest multipartRequest = resolver
				.resolveMultipart(request);

		if (StringUtils.isEmpty(inputName) || StringUtils.isEmpty(actionId)
				|| StringUtils.isEmpty(actionType)) {
			OutputUtil.returnSuccess(response, false, "传入参数不完整");
		}
		
		String filePath = PathManager.FILE_BASEPATH;// 服务器文件地址
		String mappingPath = "/"+ProjectInfor.PROJECT_NAME+"/"+actionType;// 映射文件地址
		
		/** 保存目录的真实路径 **/
		filePath += mappingPath;

		/** 根据真实路径创建目录 **/
		File logoSaveFile = new File(filePath);
		if (!logoSaveFile.exists()) {
			logoSaveFile.mkdirs();
		}
		/** 页面控件的文件流 **/
		MultipartFile multipartFile = multipartRequest.getFile(inputName);
		/** 获取文件的后缀 **/
		String originalFilename = multipartFile.getOriginalFilename();
		String suffix = originalFilename.substring(originalFilename
				.lastIndexOf("."));
		/** 文件类型 **/
		String fileType = suffix.substring(1, suffix.length());

		/** 拼成完整的文件保存路径加文件 **/
		UUID uuid = UUID.randomUUID();
		String fileName = filePath + "/" + File.separator + uuid;

		File file = null;
		if ("ppt".equals(fileType.toLowerCase()) || "pptx".equals(fileType.toLowerCase())) {
			file = new File(fileName+"."+fileType);
		}else {
			file = new File(fileName);
		}

		//String data = file.getPath();
		try {
			multipartFile.transferTo(file);
		} catch (IllegalStateException e) {
			isSuccess = false;
			errorInfo = "文件保存异常！";
			e.printStackTrace();
		} catch (IOException e) {
			isSuccess = false;
			errorInfo = "文件保存异常！";
			e.printStackTrace();
		}
		if (isSuccess) {
			//PPT处理成PDF，PDF处理成图片
			if ("ppt".equals(fileType.toLowerCase()) || "pptx".equals(fileType.toLowerCase())) {
				File pdfFile = new File(fileName+".pdf");
				//PDF_2_Image_Util.imgMerageToPdf(new File("E:\\testImage").listFiles(),new File("E:","巴黎公社活动家传略.pdf"));
				//OfficeConverterUtil.pptToImg(file.getPath(), pdfFile.getPath());
				PPT_2_JPG_2_PDF_Util.pptToPdf(file, pdfFile);
				//PPT_2_PDF_Util.ppt2PDF(file, pdfFile);
			}
			// 保存数据到数据库
			Map<String, Object> inputMap = new HashMap<String, Object>();
			inputMap.put("fileTitle", fileTitle);
			inputMap.put("fileType", fileType);
			inputMap.put("filePath", mappingPath);
			inputMap.put("uuid", uuid);
			inputMap.put("fileName", originalFilename);
			errorInfo = mappingPath+"/"+uuid;
			isSuccess = attachmentService.add(userName, actionType, actionId,
					inputMap);
			if (actionType.equals("avatar")) {
				SessionUtil.setSession(request, SessionData.photoUrlKey, mappingPath+"/"+uuid);
			}
		}
		
		OutputUtil.returnSuccess(response, isSuccess, errorInfo);
	}

	/**
	 * 附件下载
	 * 
	 * @param request
	 * @param response
	 * @param ids
	 * @author ServerZhang
	 * @date 2016年7月20日
	 */
	@RequestMapping("download/{id}")
	public void download(HttpServletRequest request,
			HttpServletResponse response, @PathVariable Integer id) {
		
		Map<String, Object> form = attachmentService.getForm(id);
		String path = null;
		String fileName = "未知文件名";
		if (form.size() > 0) {
			Object pathObj = form.get("filePath");
			Object uuidObj = form.get("uuid");
			Object nameObj = form.get("fileName");
			Object typeObj = form.get("fileType");
			if (pathObj != null && uuidObj != null) {
				path = pathObj.toString()+"/"+uuidObj.toString();
				if (nameObj != null) {
					fileName = nameObj.toString();
				}
				/*if (typeObj != null) {
					fileName += typeObj.toString();
				}*/
			}else {
				return;
			}
		}else {
			return;
		}
		File file = new File(PathManager.FILE_BASEPATH+path);
		ByteArrayOutputStream bos = null;
		BufferedInputStream in = null;
		OutputStream outputStream = null;
		try {
			bos = new ByteArrayOutputStream((int) file.length());

			in = new BufferedInputStream(new FileInputStream(file));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			byte[] data = bos.toByteArray();
			String realFileName = URLEncoder.encode(fileName, "UTF-8");
			response.reset();
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ realFileName + "\"");
			response.addHeader("Content-Length", "" + data.length);
			response.setContentType("application/octet-stream;charset=UTF-8");
			outputStream = new BufferedOutputStream(response.getOutputStream());
			outputStream.write(data);
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
			// isSuccess = false;
			// throw new FileReadException("文件读取发生错误");
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 清除附件记录并从服务器上删除文件
	 * @param request
	 * @param response
	 * @param ids
	 * @author ServerZhang
	 * @date 2016年7月20日
	 */
	@RequestMapping("clear/{ids}")
	public void clear(HttpServletRequest request,
			HttpServletResponse response, @PathVariable String ids){
		Integer clear = attachmentService.clear(ids);
		OutputUtil.returnString(response, clear.toString());
	}
	 /**
	 * 视频预览
	 * @param request
	 * @param id
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月4日
	 */
	@RequestMapping("videoView/{id}")
	public ModelAndView videoView(HttpServletRequest request, @PathVariable Integer id){
		ModelAndView mv = new ModelAndView("common/videoView");
		Map<String, Object> form = attachmentService.getForm(id);
		Object typeObj = form.get("fileType");
		Object pathObj = form.get("filePath");
		Object uuidObj = form.get("uuid");
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		
		if (typeObj != null && pathObj != null && uuidObj != null) {
			mv.addObject("url",serverBuffer.toString()+pathObj.toString()+"/"+uuidObj.toString());
			mv.addObject("type",typeObj.toString());
		}
		return mv;
	}
	/**
	 * 音频预览
	 * @param request
	 * @param id
	 * @return
	 * @author ServerZhang
	 * @date 2016年8月5日
	 */
	@RequestMapping("audioView/{id}")
	public ModelAndView audioView(HttpServletRequest request, @PathVariable Integer id){
		ModelAndView mv = new ModelAndView("common/audioView");
		Map<String, Object> form = attachmentService.getForm(id);
		Object typeObj = form.get("fileType");
		Object pathObj = form.get("filePath");
		Object uuidObj = form.get("uuid");
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		
		if (typeObj != null && pathObj != null && uuidObj != null) {
			mv.addObject("url",serverBuffer.toString()+pathObj.toString()+"/"+uuidObj.toString());
			mv.addObject("type",typeObj.toString());
		}
		return mv;
	}
	/**
	* 图文查看
	* @author  作者 : wufeng
	* @date 创建时间：2016年8月18日 下午4:05:08 
	* @return  
	*/
	@RequestMapping("picView/{id}")
	public ModelAndView picView(HttpServletRequest request, @PathVariable Integer id){
		ModelAndView mv = new ModelAndView("common/picView");
		mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
		mv.addObject("course_res_id", id);
		return mv;
	}
	/**
	 * PPT预览
	 * @param request
	 * @param id
	 * @return
	 * @author ServerZhang
	 * @date 2016年9月23日
	 */
	@RequestMapping("pptView/{id}")
	public ModelAndView pptView(HttpServletRequest request,
			@PathVariable Integer id) {
		ModelAndView mv = new ModelAndView("study/web/viewer1");
		// 通过资源ID获取pdf的地址
		Map<String, Object> form = attachmentService.getForm(id);
		StringBuffer pdfUrl = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		pdfUrl.append("http://").append(serverName).append(":")
				.append(serverPort).append("/")
				.append(PathManager.FILE_MAPPING).append(form.get("filePath"))
				.append("/").append(form.get("uuid")).append(".pdf");
		mv.addObject("pdfUrl", pdfUrl);
		mv.addObject("isPPT", 1);
		return mv;
	}

	@RequestMapping("update/field")
	public void updateField(HttpServletRequest request,HttpServletResponse response){
		String operator = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		String id = request.getParameter("id");
		String fileTitle = request.getParameter("fileTitle");
		String note = request.getParameter("note");
		if (StringUtils.isEmpty(id)) {
			OutputUtil.returnSuccess(response, false);
			return;
		}
		Map<String, Object> inputMap = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(fileTitle)) {
			inputMap.put("fileTitle", fileTitle);
		}
		if (!StringUtils.isEmpty(note)) {
			inputMap.put("note", note);
		}
		Boolean update = attachmentService.update(operator, id, inputMap);
		OutputUtil.returnSuccess(response, update);
	}
}
